package org.flashbrighton.as3bots.display
{
	import flash.display.DisplayObject;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.MouseEvent;
	import flash.events.ProgressEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.FileFilter;
	import flash.net.FileReference;
	
	import org.flashbrighton.as3bots.bots.BaseBot;
	import org.flashbrighton.as3bots.bots.DummyBot;
	import org.flashbrighton.as3bots.bots.JoesBot;
	import org.flashbrighton.as3bots.display.templates.BotDescriptionRow;
	import org.flashbrighton.as3bots.display.templates.LoadBotTemplate;
	import org.flashbrighton.as3bots.utils.BotLoader;
	
	public final class LoadBotPage extends Sprite
	{
		
		protected var fileRef : FileReference ;
		protected var botLibrary : Vector.<BaseBot> = new Vector.<BaseBot>;
		protected var bots : Vector.<BaseBot> = new Vector.<BaseBot>;
		
		protected var template : LoadBotTemplate ;
		
		public function LoadBotPage( botLibrary : Vector.<BaseBot>, bots : Vector.<BaseBot> )
		{
			this.botLibrary = botLibrary;
			this.bots= bots;
			botLibrary.push( new DummyBot );
			
			addEventListener( Event.ADDED_TO_STAGE , handleAddedToStage );
		}
		
		protected function disableButton( s:Sprite ):void
		{
			s.alpha = 0.2;
			s.mouseEnabled = false;
		}
		
		protected function enableButton( s:Sprite ):void
		{
			s.alpha = 1;
			s.mouseEnabled =true;
		}
		
		protected function refresh():void
		{
			while( template.libraryBotsContainer.numChildren ) template.libraryBotsContainer.removeChildAt( 0 );
			while( template.selectedBotsContainer.numChildren ) template.selectedBotsContainer.removeChildAt( 0 );
			
			for each( var bot : BaseBot in botLibrary  )
			{
				var botDescription : BotDescriptionRow = new BotDescriptionRow();
				
				botDescription.nameTextField.text = bot.botName
				botDescription.y = template.libraryBotsContainer.numChildren * 20;
				botDescription.buttonMode = true;
				botDescription.addEventListener( MouseEvent.CLICK , handleLibraryRowClick );
				template.libraryBotsContainer.addChild( botDescription );
			}
			
			for each( bot in bots  )
			{
				botDescription = new BotDescriptionRow();
				
				botDescription.nameTextField.text = bot.botName
				botDescription.y = template.selectedBotsContainer.numChildren * 20;
				botDescription.buttonMode = true;
				botDescription.addEventListener( MouseEvent.CLICK , handleRowClick );
				template.selectedBotsContainer.addChild( botDescription );
				
			}
			
			if( bots.length >= 2 ) enableButton( template.startButton );
			else disableButton( template.startButton )
			
		}
		
		protected function onPersonalBotLoad( botClass :  BaseBot ):void
        {
        	botLibrary.push( botClass );
        	if( botLibrary.length > 10 ) botLibrary.shift();

        	refresh();
        }

        protected function onPersonalBotLoadFailure( error : String ):void
        {
        	debug( error );
        }

		public function handleAddedToStage( e : Event ):void
		{
			addChild( template = new LoadBotTemplate( stage.stageWidth, stage.stageHeight ) );
			template.loadButton.addEventListener( MouseEvent.CLICK, handleLoadClick );
			template.startButton.addEventListener( MouseEvent.CLICK, handleStartClick );
			disableButton( template.startButton );
			refresh();
			
			
		}
		
				
		protected function handleLoadClick(e:Event):void
		{
			fileRef = new FileReference();
            fileRef.addEventListener(Event.SELECT, handleFileSelected);
            fileRef.addEventListener(Event.CANCEL, handleCancel);
            fileRef.addEventListener(IOErrorEvent.IO_ERROR, handleIOError);
            fileRef.addEventListener(SecurityErrorEvent.SECURITY_ERROR,
                        handleSecurityError);
            var textTypeFilter:FileFilter = new FileFilter("Compiled Bot (*.swf)",
                        "*.swf");
            fileRef.browse([textTypeFilter]);
		}
		
		protected function handleStartClick( e:Event ):void
		{
			dispatchEvent( new Event( Event.COMPLETE ) );
		}
		
		protected function handleLibraryRowClick( e:MouseEvent ):void
		{
			var i : int = template.libraryBotsContainer.getChildIndex( e.target as DisplayObject );
			var botClass : Class = Object( botLibrary[i] ).constructor ;
			if( botClass )
			{
				bots.push( new botClass );
				if( bots.length > 10 ) bots.shift();
				refresh();
			}
		}
		
		protected function handleRowClick( e:MouseEvent ):void
		{
			var i : int = template.selectedBotsContainer.getChildIndex( e.target as DisplayObject );
			var botClass : Class = Object( bots[i] ).constructor ;
			if( botClass )
			{
				bots.splice(i,1);
				refresh();
			}
		}

        protected function handleIOError(evt:IOErrorEvent):void
        {
            debug("There was an IO Error.");
        }
        protected function handleSecurityError(evt:Event):void
        {
            debug("There was a security error.");
        }

		public function handleFileSelected(evt:Event):void
        {
            fileRef.addEventListener(ProgressEvent.PROGRESS, handleProgress);
            fileRef.addEventListener(Event.COMPLETE, handleComplete);
            fileRef.load();
        }

        public function handleProgress(evt:ProgressEvent):void
        {
            //debug("Loaded " + evt.bytesLoaded + " of " + evt.bytesTotal + " bytes.");
        }

        public function handleComplete(evt:Event):void
        {
        	var botLoader : BotLoader = new BotLoader( fileRef.name.replace(/\.[^.]+$/,'')+'Bot' , onPersonalBotLoad , onPersonalBotLoadFailure );
        	/*var loader : Loader = new Loader();

        	var context:LoaderContext = new LoaderContext();
	        context.applicationDomain = ApplicationDomain.currentDomain;
			context.applicationDomain = new ApplicationDomain();

        	loader.contentLoaderInfo.addEventListener( Event.COMPLETE , handleLoadComplete );
        	loader.loadBytes( evt.target.data, context );
        	*/

            debug("File was successfully loaded.");
            botLoader.loadBytes( evt.target.data );

        }

        protected function handleCancel(evt:Event):void
        {
            debug("The browse request was canceled by the user.");
        }

        protected function debug( s:String ):void
        {
        	template.debugTextField.text += s+'\n';
        	template.debugTextField.scrollV = template.debugTextField.maxScrollV;
        }

	}
}